package org.blade.personal.framework.asm;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;


/**
 * 通过asm动态生成Employee类的字节码文件
 * @author Administrator
 *
 */
public class GeneratorEmpClass {

	public static void main(String[] args) throws IOException {
		
		//ClassWriter用于生成类
		ClassWriter writer = new ClassWriter(0);
		
		//通过visit生成类的头部信息
		writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, "com/study/Emp", null, null, null);
		
		//定义类Employee的属性 no和age
		writer.visitField(Opcodes.ACC_PUBLIC+Opcodes.ACC_FINAL+Opcodes.ACC_STATIC, "no",  "I", null, new Integer(1)).visitEnd();
		//属性age：private static final age=8
		writer.visitField(Opcodes.ACC_PUBLIC+Opcodes.ACC_FINAL+Opcodes.ACC_STATIC, "age", "I",  null, new Integer(8)).visitEnd();
		
		//定义类的方法
		writer.visitMethod(Opcodes.ACC_PUBLIC, "test","(Ljava/lang/String;)V" , null, null).visitEnd();
		
		//完成
		writer.visitEnd();
		
		//将writer字节数组写到文件里面去
		byte[] byArr = writer.toByteArray();
		File file = new File("D://Emp.class");
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(byArr);
		fos.close();
	}

}
